package com.hxl.tech.gateway.auth.controller;


import com.hxl.tech.gateway.auth.model.Application;
import com.hxl.tech.gateway.auth.service.ApplicationService;
import com.hxl.tech.gateway.common.constant.AppConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpSession;
import java.util.Objects;


/**
 * OAuth2授权码模式登录
 * @author soliddq
 * @date 2023-10-10
 */
@Slf4j
@ApiIgnore
@Controller
@RequiredArgsConstructor
public class OAuthController {

    private final ApplicationService applicationService;

    @RequestMapping("/login")
    public String login(Model model) {

        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession httpSession = attr.getRequest().getSession(true);
        DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest)httpSession.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        log.debug("OAuth授权码模式访问，" + defaultSavedRequest);

        String appId = defaultSavedRequest.getParameterValues("client_id")[0];
        Application application = applicationService.readForOAuth(appId);
        if(Objects.isNull(application) || application.getState() != AppConstant.StateEnum.ENABLE) {
            model.addAttribute("error", "应用不存在或状态不正确");
        }
        log.debug("授权应用Id:[{}], 应用名:[{}], 应用状态:[{}]", appId, application.getAppName(), application.getState());
        return "login";
    }
}
